(function(){
  var client, destination;
  destination ="/amis/demo";
  var debug = function(str) {
    console.log("[MQTT]",str);
  };  
  /**
   * A function to initialize MQTT connection and set up client with given host, port, and clientId.
   *
   */
  function init_mqtt() {
    var host = "localhost";   
    var port = "15675";
    var clientId = "clientId-" + parseInt(Math.random() * 100000);

    client = new Messaging.Client(host, Number(port), clientId);

    client.onConnect = onConnect;
  
    client.onMessageArrived = onMessageArrived;
    client.onConnectionLost = onConnectionLost;            

    client.connect({userName:'admin', password:'admin', onSuccess:onConnect, onFailure:onFailure}); 
  }
  
  // the client is notified when it is connected to the server.
  var onConnect = function(frame) {
    debug("connected to MQTT");
    client.subscribe(destination);
  };

  function onFailure(failure) {
    debug("failure");
    debug(failure.errorMessage);
  }
  
  function onMessageArrived(message) {
    debug(message.destinationName+","+message.payloadString);  
  }

  function onConnectionLost(responseObject) {
    console.log("onConnectionLost.");
    if (responseObject.errorCode !== 0) {
      debug(client.clientId + ": " + responseObject.errorCode + "\n");
    }
    init_mqtt();
  }
  init_mqtt();
})();